<template>
    <div class="inputContent">
        <el-input
            :id="`inputContent-key`"
            v-model="inputValue"
            class="input-content-textarea"
            type="textarea"
            :disabled="props.disabled || props.inputDisabled"
            :rows="props.rows"
            :maxlength="props.maxLength"
            :placeholder="props.placeholder"
            show-word-limit
            @input="changeWords" />
        <div class="input-content-config">
            <div class="config-left">
                <div v-for="item in tabs" :key="item?.name" class="input-content-item">
                    <component
                        :is="item.comName"
                        v-if="item?.comName"
                        :disabled="props.disabled || props.inputDisabled"
                        @change="selectEmoji" />
                    <span
                        v-else
                        class="item-text"
                        :class="{
                            insert: ![1, 2].includes(item.name),
                            disabled: props.disabled || props.inputDisabled
                        }"
                        @click="tabHandleClick(item)">
                        {{ item?.label }}
                    </span>
                </div>
            </div>
        </div>
    </div>

    <ZwMaterialLib
        ref="ZWMaterialLibRef"
        v-model="materialLibShow"
        :show-tabs-list="[0]"
        :max-num="9"
        @submit="getMaterialLib" />
</template>

<script setup lang="ts">
import { reactive, ref, computed, watch, onMounted, nextTick, shallowRef, onUnmounted, withDefaults } from 'vue';
import ZwMaterialLib from '../../ZwUnityKitMaterialLib/index.vue';
import Emoji from './Emoji.vue';

interface Props {
    /** 输入框tab，1-展示选择文本 2-展示选择表情 */
    tabs?: Array<any>;
    /** 输入框自定义文案插入内容 */
    tabsText?: Array<any>;
    /** 输入框placeholder */
    placeholder?: string;
    /** 文本输入框最近长度 */
    maxLength?: number;
    /** 文本输入内容回显使用 */
    content?: string;
    singleList?: any;
    /** 输入框高度 */
    rows?: number;
    /** 输入框是否禁用 */
    inputDisabled?: boolean;
    /** 整个素材是否禁用 */
    disabled?: boolean;
    /** 场景值 */
    sceneValue?: string;
}

const props = withDefaults(defineProps<Props>(), {
    tabs: () => [],
    tabsText: () => [],
    placeholder: '',
    maxLength: 1000,
    content: '',
    singleList: () => [],
    rows: 6,
    inputDisabled: false,
    disabled: false,
    sceneValue: 'friend'
});

const emit = defineEmits(['update:modelValue', 'change']);

/** 素材弹框 ref */
const ZWMaterialLibRef = ref<any>('');

/** 素材弹框是否展示 */
const materialLibShow = ref<boolean>(false);

/** input内容 */
const inputValue = ref<any>('');

/** 选择文本id */
const text_ids = reactive<any>([]);

/** tabs */
const tabsList = reactive<Array<any>>([
    {
        label: '选择文本',
        value: '',
        name: 1
    },
    {
        label: '😊',
        value: '',
        name: 2,
        comName: shallowRef(Emoji)
    }
]);

const tabs = computed(() => {
    const list: any = tabsList.filter(item => props.tabs?.includes(item.name)) || [];
    if (props.tabsText.length) {
        props.tabsText?.map((el: any) => {
            list.push({
                label: `#${el}#`,
                value: `##${el}##`
            });
        });
    }
    return list;
});

/** 输入框改变 */
const changeWords = () => {
    emit('change', inputValue.value);
};

const tabHandleClick = tab => {
    if (props.disabled || props.inputDisabled) return;
    const { name, value } = tab;
    if (name) {
        switch (Number(name)) {
            case 1:
                selectText();
                break;
            default:
                insertName(tab?.value);
                break;
        }
    } else if (value) {
        insertName(value);
    }
};

const btnHandle = item => {
    const { value } = item;
    switch (value) {
        case 1:
            clear();
            break;
    }
};

/** 清空输入框 */
const clear = () => {
    inputValue.value = '';
    changeWords();
};

/** 选择文本打开素材弹框 */
const selectText = () => {
    ZWMaterialLibRef.value.tabsType = 0;
    ZWMaterialLibRef.value.selectInfo.materialList = [];
    materialLibShow.value = true;
};

/** 设置表情 */
const selectEmoji = ({ value }) => {
    insertInputContent(value);
};

const insertName = name => {
    insertInputContent(name);
};

/** 获取选中素材库内容 */
const getMaterialLib = res => {
    const { selectList, type } = res[0];
    if (type === 0) {
        const str = selectList.reduce((pre, next) => {
            return pre + next.content;
        }, '');
        const arr: any = selectList.map(item => item.id);
        text_ids.push(...arr);
        insertInputContent(str);
    }
};

const insertInputContent = content => {
    const arr = Array.from(inputValue.value);
    if (arr.length >= props.maxLength) {
        return;
    }
    const el: any = document.getElementById(`inputContent-key`);
    const inpIndex = el.selectionStart;
    const textareaContent = inputValue.value;
    const start = `${textareaContent.substring(0, inpIndex)}${content}`;
    const end = textareaContent.substring(inpIndex, textareaContent.length);
    if (props.singleList.includes(0)) {
        inputValue.value = content;
    } else {
        inputValue.value = `${start}${end}`;
    }
    inputValue.value = `${start}${end}`.slice(0, props.maxLength);
    // inputValue.value = Array.from(inputValue.value).splice(0, props.maxLength).join('');
    changeWords();
    nextTick(() => {
        el.selectionStart = start.length;
        el.selectionEnd = start.length;
        el.focus();
    });
};

const init = val => {
    inputValue.value = val;
    nextTick(() => {
        changeWords();
    });
};

const clearInput = () => {
    init('');
};

watch(
    () => props.content,
    val => {
        init(val);
    },
    { immediate: true, deep: true }
);

onMounted(() => {});

onUnmounted(() => {});

defineExpose({
    inputValue,
    insertInputContent,
    clearInput
});
</script>

<style lang="scss" scoped>
$color: #e9e9e9;
$border: 1px solid $color;

.inputContent {
    border: 1px solid #e9e9e9;
    padding: 6px;
    padding-bottom: 0;
    border-radius: 4px;

    .input-content-textarea {
        :deep(.el-textarea__inner) {
            box-shadow: 0 0 0 0 var(--el-input-border-color, var(--el-border-color)) inset;
            resize: none;
            cursor: default;
            padding: 2px;
            background-color: transparent;
            border: none;
        }
    }

    .input-content-config {
        height: 40px;
        border-top: $border;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .config-left {
            display: flex;
            align-items: center;

            .input-content-item {
                margin-right: 10px;
                display: flex;
                align-items: center;
                height: 16px;
                border-right: 1px solid #e9e9e9;
                padding: 0 8px;

                &:last-of-type {
                    border: none;
                }

                &:hover {
                    cursor: pointer;
                }

                .item-text {
                    font-size: 12px;
                    line-height: 1;
                    color: #555;
                    white-space: nowrap;

                    &:hover {
                        color: #f96b02;
                    }
                }

                // .insert{
                //   color: #F96B02;
                //   &:hover{
                //     color: #F98B33;
                //   }
                // }
                .disabled {
                    color: #888;

                    &:hover {
                        cursor: not-allowed;
                        color: #888;
                    }
                }
            }
        }

        .config-right {
            margin-left: 16px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
    }
}
</style>
